package com.itcc.controller;

import com.itcc.entity.Browse;
import com.itcc.entity.User;
import com.itcc.service.BrowseService;
import com.itcc.service.impl.BrowseServiceImpl;
import com.itcc.utils.Constants;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/browse")
public class BrowseController extends BaseServlet{

    public String show(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            // 用户未登录，可能需要重定向到登录页面
            return "redirect:/login";
        }
        int uid = user.getUid();

        BrowseService browseService =new BrowseServiceImpl();
        List<Browse> browseList=browseService.findBrowsesByUid(String.valueOf(uid));
        if (browseList == null || browseList.isEmpty()) {
            System.out.println("browseList is empty or null");
        } else {
            System.out.println("browseList contains " + browseList.size() + " records");

        }

        request.setAttribute("browseList", browseList);

        return Constants.FORWARD+"browse_history.jsp";
    }

    public String showAdminBrowse(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null || user.getUrole() != 1) {
            // 非管理员或未登录，重定向到登录页面
            return Constants.REDIRECT + "/login.jsp";
        }

        String targetUid = request.getParameter("uid");
        if (targetUid == null) {
            // 没有指定用户ID，返回错误信息
            request.setAttribute("msg", "未指定用户ID");
            return Constants.FORWARD + "/error.jsp";
        }

        BrowseService browseService = new BrowseServiceImpl();
        List<Browse> browseList = browseService.findBrowsesByUid(targetUid);
        request.setAttribute("browseList", browseList);

        return Constants.FORWARD + "/browse_history.jsp"; // 管理员浏览历史视图
    }

}
